package test;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class Helper {
    public static final String SING = "w51@458#123";
    public static String getToken(Collection<String > urls) {
        JWTCreator.Builder builder = JWT.create();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); //默认7天过期
        int i = 1;
        for (String url:urls){
            builder.withClaim("urlId"+i,url);
            i++;
        }
        String token = builder
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }
    public static String getToken(Map<Integer, String> map) {
        JWTCreator.Builder builder = JWT.create();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); //默认7天过期
        for(Integer urlId:map.keySet()){
            System.out.println("111");
            System.out.println(map.keySet());
            System.out.println(urlId);
            builder.withClaim(urlId+"",map.get(urlId));
        }
        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
         String token = builder.sign(Algorithm.HMAC256(SING));//签名
        return token;
    }
    public static Collection<String> verify(String token, HttpServletResponse response) throws IOException {
        JSONObject message = new JSONObject();
        Collection<String> collections = new LinkedList<>();
        try {
            //创建验证对象
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            int num = 1;
            //解码对象
            int size = verify.getClaims().size();
            for (int i = 1; i < size; i++) {
                System.out.println(collections.add(verify.getClaim("urlId"+num).asString()));
                collections.add(verify.getClaim("urlId"+num).asString());
                num++;
            }
            /*for (int i = 1; i < size; i++) {
                collections.add(verify.getClaim(i+"").asString());
            }*/
            message.put("message","请求成功");
        } catch (Exception e) {
            message.put("message", "没有权限");
            e.printStackTrace();
        }
        response.getWriter().println(message);
        return collections;
    }
}
